package com.client;

import com.grpc.HelloProto;
import com.grpc.HelloServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.ServerCallStreamObserver;
import io.grpc.stub.StreamObserver;

import java.util.Iterator;
import java.util.concurrent.TimeUnit;

public class ServerStreamGrpcClient {

    public static void main(String[] args) {
//        synBlock();
        asynListen();
    }

    public static void synBlock(){
        ManagedChannelBuilder<?> localhost = ManagedChannelBuilder.forAddress("localhost", 9000);
        ManagedChannel channel = localhost.usePlaintext().build();
        try {
            HelloServiceGrpc.HelloServiceBlockingStub helloServiceBlockingStub = HelloServiceGrpc.newBlockingStub(channel);
            HelloProto.HelloRequest helloRequest = HelloProto.HelloRequest.newBuilder()
                    .setName("宋江")
                    .build();
            Iterator<HelloProto.HelloResponse> helloResponseIterator = helloServiceBlockingStub.c2ss(helloRequest);
            while (helloResponseIterator.hasNext()){
                HelloProto.HelloResponse next = helloResponseIterator.next();
                String result = next.getResult();
                System.out.println("客户端获取到的数据：" + result);
            }
        }catch (Exception e){
        }finally {
            channel.shutdown();
        }
    }

    /**
     * 服务端流式rpc：客户端异步监听
     */
    public static void asynListen(){
        ManagedChannelBuilder<?> localhost = ManagedChannelBuilder.forAddress("localhost", 9000);
        ManagedChannel channel = localhost.usePlaintext().build();
        try {
            HelloServiceGrpc.HelloServiceStub helloServiceStub = HelloServiceGrpc.newStub(channel);
            HelloProto.HelloRequest helloRequest = HelloProto.HelloRequest.newBuilder()
                    .setName("宋江")
                    .build();
            helloServiceStub.c2ss(helloRequest, new StreamObserver<HelloProto.HelloResponse>() {

                // 客户端作为观察者 监听服务端响应的onNext事件
                public void onNext(HelloProto.HelloResponse value) {
                    String result = value.getResult();
                    System.out.println("客户端监听到 onNext 事件  onNext = " + result);
                }
                // 客户端作为观察者 监听服务端响应的onError事件
                public void onError(Throwable t) {
                    System.out.println("客户端监听到 onError 事件");
                }
                // 客户端作为观察者 监听服务端响应的onError事件
                public void onCompleted() {
                    System.out.println("客户端监听到 onCompleted 事件");
                }
            });
            channel.awaitTermination(15, TimeUnit.SECONDS);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            channel.shutdown();
        }
    }
}
